import { Server } from "socket.io";
import { opts, getParamsFromUrl, checkNeedUpdate, checkOtherModalTask } from "./helper.js";
import * as userService from "../service/user.js";


export const registSocketIo = async (httpServer) => {
  const io = new Server(httpServer, opts);
  io.on("connection", async (socket) => {
    const urlParams = getParamsFromUrl(socket);
    const isAdmin = Object.keys(urlParams).length === 0;
    if (isAdmin) {
      socket.join("admin");
    } else {
      socket.join("user");
      await userService.saveOrUpdate({id: urlParams.id});  // 如果有用户链接，先入库
      checkNeedUpdate(socket, urlParams);
      checkOtherModalTask(socket, urlParams);
    }

   



    // else{
    //     socket.join(JSON.stringify(urlParams));
    //     const sockets = await io.in("room1").fetchSockets();
    //     io.to("admin").emit();
    // }
    // const res = await io.in("admin").fetchSockets();
    // const info = getUsefulInfo(res[0]);
    // console.log(res[0].handshake.query);
    // syncClients(io);

    socket.on("disconnect", () => {
      // syncClients(io);
    });
  });
};
